// Chemical Dosage Pump Data Source for MCP Server
// MCP服务器的化学加药泵数据源
class ChemicalDosageDataSource {
  constructor() {
    this.status = {
      pump1: {
        status: 'stopped', // running, stopped, fault
        frequency: 0, // Hz
        flowRate: 0, // m³/h
        dosageAmount: 0 // kg
      },
      pump2: {
        status: 'stopped',
        frequency: 0,
        flowRate: 0,
        dosageAmount: 0
      },
      totalDosageToday: 0,
      timestamp: new Date()
    };
    this.simulateOperation();
  }

  // Simulate pump operation
  // 模拟泵操作
  simulateOperation() {
    setInterval(() => {
      // Randomly update pump status
      // 随机更新泵状态
      if (Math.random() > 0.7) {
        this.status.pump1.status = 'running';
        this.status.pump1.frequency = 30 + Math.random() * 20; // 30-50 Hz
        this.status.pump1.flowRate = 5 + Math.random() * 10; // 5-15 m³/h
        this.status.pump1.dosageAmount += this.status.pump1.flowRate * 0.01;
      } else {
        this.status.pump1.status = 'stopped';
        this.status.pump1.frequency = 0;
        this.status.pump1.flowRate = 0;
      }

      if (Math.random() > 0.8) {
        this.status.pump2.status = 'running';
        this.status.pump2.frequency = 30 + Math.random() * 20;
        this.status.pump2.flowRate = 3 + Math.random() * 7;
        this.status.pump2.dosageAmount += this.status.pump2.flowRate * 0.01;
      } else {
        this.status.pump2.status = 'stopped';
        this.status.pump2.frequency = 0;
        this.status.pump2.flowRate = 0;
      }

      this.status.totalDosageToday = this.status.pump1.dosageAmount + this.status.pump2.dosageAmount;
      this.status.timestamp = new Date();
    }, 5000);
  }

  // Get current pump status
  // 获取当前泵状态
  getData() {
    return this.status;
  }

  // Execute command (start/stop pump, adjust frequency)
  // 执行命令（启动/停止泵，调整频率）
  executeCommand(command) {
    console.log(`Executing command on ChemicalDosageDataSource: ${command}`);
    console.log(`在ChemicalDosageDataSource上执行命令: ${command}`);
    // Parse and execute command
    // 解析并执行命令
    // In a real implementation, this would interact with actual PLCs
    // 在实际实现中，这将与实际的PLC交互
    try {
      const cmd = JSON.parse(command);
      if (cmd.type === 'start_pump') {
        this.status[`pump${cmd.pumpId}`].status = 'running';
        return true;
      } else if (cmd.type === 'stop_pump') {
        this.status[`pump${cmd.pumpId}`].status = 'stopped';
        return true;
      } else if (cmd.type === 'set_frequency') {
        this.status[`pump${cmd.pumpId}`].frequency = cmd.frequency;
        return true;
      }
    } catch (e) {
      console.error('Failed to parse command:', command);
      console.error('无法解析命令:', command);
      return false;
    }
    return false;
  }
}

module.exports = ChemicalDosageDataSource;